package com.xiaoxin.yixinai._frame.config;

import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.xiaoxin.yixinai.userinfo.UserInfo;
import com.xiaoxin.yixinai.userinfo.UserInfoService;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

	@Resource
	private UserInfoService userInfoService;
	
	@Override
	public UserDetails loadUserByUsername(String arg0) throws UsernameNotFoundException {
		UserInfo user = userInfoService.findByLoginName(arg0.trim());
		if (user == null)
			throw new UsernameNotFoundException("username not found");
		
		/* 上面的 findByLoginName 返回的字段不全，这里先再用ID查询一次吧 */
		user = userInfoService.findOne(user.getUserId());
		
		List<SimpleGrantedAuthority> authorities = new LinkedList<SimpleGrantedAuthority>();
		
		// 通过userId查询菜单权限
//		List<MenuInfo> menuInfoList = menuInfoService.findByUserId(user.getId());
//		if (menuInfoList != null && !menuInfoList.isEmpty()) {
//			for (MenuInfo menuInfo: menuInfoList) {
//				authorities.add(new SimpleGrantedAuthority(menuInfo.getMenuCode()));
//			}
//		}
		
		LoginUser loginUser = new LoginUser(user, authorities);
		return loginUser;
	}

}
